import React, { useState, useEffect } from 'react';
import { Layout, Menu, Avatar, Dropdown, Input, Button, Upload, message, List } from 'antd';
import { UserOutlined, UploadOutlined, SendOutlined, PlusOutlined } from '@ant-design/icons';
import { history, } from '@umijs/max';
import type { MenuProps } from 'antd';

// 引入服务
import {
  uploadFile,
  decorationCell,
  userCellTitleList,
  userCellList,
  cellFileId,
  userCount,
} from './service';

const { Header, Sider, Content, Footer } = Layout;
const { TextArea } = Input;

const items: MenuProps['items'] = [
  {
    key: '1',
    label: '退出登录',
  },
];

interface MessageItem {
  text: string;
  type: 'user' | 'bot';
  time: string;
}

interface HistoryItem {
  id: number;
  userId: number;
  cellId: string;
  title: string;
}

interface FileItem {
  id: number;
  fileId: string;
  cellId: string;
  effectiveTime: string;
}

interface UploadedFile {
  id: string; // fileId
  name: string; // 文件名
}

const App: React.FC = () => {
  const [messages, setMessages] = useState<MessageItem[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [currentCellId, setCurrentCellId] = useState<string | null>(null);
  const [historyList, setHistoryList] = useState<HistoryItem[]>([]);
  const [uploadedFiles, setUploadedFiles] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [paidCount, setPaidCount] = useState<number>(0);
  const [freeCount, setFreeCount] = useState<number>(0);

  // 获取历史记录
  const fetchHistory = async () => {
    try {
      // const response = await userCellTitleList();
      // const resuserCount = await userCount()
      const [response, resuserCount] = await Promise.all([userCellTitleList(), userCount()])
      if (response.code === 0) {
        setHistoryList(response.data);

        // 如果没有当前对话且有历史记录，加载第一个
        // if (response.data.length > 0 && !currentCellId) {
        //   setCurrentCellId(response.data[0].cellId);
        //   loadConversation(response.data[0].cellId);
        // }
      } else {
        throw new Error(response.msg || '获取历史记录失败');
      }
      if (resuserCount.code === 0) {
        setPaidCount(resuserCount?.data.paidCount)
        setFreeCount(resuserCount?.data.freeCount)
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 加载具体对话
  const loadConversation = async (cellId: string) => {
    try {
      const [conversationRes, filesRes] = await Promise.all([
        userCellList({ cellId }),
        cellFileId({ cellId })
      ]);

      if (conversationRes.code === 0 && filesRes.code === 0) {
        // 设置文件
        const fileIds = filesRes.data.map(f => f.fileId);
        setUploadedFiles(fileIds);
        setCurrentCellId(cellId);
        // 转换消息格式
        const formattedMessages = conversationRes.data.map(item => ({
          text: item.message,
          type: item.messageRoleId === 1 ? 'user' : 'bot',
          time: formatTime(item.createTime)
        }));
        setMessages(formattedMessages);
      } else {
        throw new Error('加载对话详情失败');
      }
    } catch (error) {
      message.error('加载对话记录失败');
    }
  };

  // 格式化时间
  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr);
    return date.toLocaleTimeString([], {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 发送消息
  const handleSend = async () => {
    if (!inputValue.trim() || loading) return;

    const now = new Date().toLocaleTimeString([], {
      hour: '2-digit',
      minute: '2-digit'
    });

    // 添加用户消息
    const userMessage: MessageItem = {
      text: inputValue,
      type: 'user',
      time: now
    };

    setMessages(prev => [...prev, userMessage]);
    setLoading(true);

    try {
      const fileIdList = uploadedFiles
        .filter(file => file.id != null)  // 过滤掉 null 和 undefined
        .map(file => file.id);            // 确保剩下的都有 id
      const response = await decorationCell({
        cellId: currentCellId || "",
        fileId: fileIdList, // 这里只传递用户没有删除的文件
        message: inputValue
      });
      if (response.code === 0) {
        // 更新cellId（如果是首次对话）
        if (!currentCellId && response.data.cellId) {
          setCurrentCellId(response.data.cellId);

          // 更新历史记录
          fetchHistory();
        }
        // 添加机器人回复
        const botMessage: MessageItem = {
          text: response.data.resultMessage,
          type: 'bot',
          time: new Date().toLocaleTimeString([], {
            hour: '2-digit',
            minute: '2-digit'
          })
        };
        setMessages(prev => [...prev, botMessage]);

        // 清空输入框
        setInputValue('');
      } else {
        throw new Error(response.msg || '机器人回复失败');
      }
    } catch (error) {
      console.error(error);
      message.error('对话失败，请稍后再试');

      // 移除用户消息
      setMessages(prev => prev.slice(0, -1));
    } finally {
      setLoading(false);
    }
  };

  // 文件上传
  const handleFileUpload = async (file: File) => {
    setLoading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await uploadFile(formData);

      if (response.code === 0) {
        message.success(`${file.name} 上传成功`);

        // 添加文件名和 fileId 到状态
        const newFile: UploadedFile = {
          id: response.data,
          name: file.name,
        };

        setUploadedFiles(prev => [...prev, newFile]);
        return response.data;
      } else {
        throw new Error(response.msg || '文件上传失败');
      }
    } catch (error) {
      console.error(error);
      message.error(`${file.name} 上传失败`);
      return null;
    } finally {
      setLoading(false);
    }
  };

  // 新建对话
  const handleNewChat = () => {
    setCurrentCellId(null);
    setMessages([]);
    setUploadedFiles([]);
  };

  // 初始化加载历史记录
  useEffect(() => {
    fetchHistory();
  }, []);

  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    if (key === '1') {
      message.success('退出登录成功');
      // TODO: 清除登录状态、跳转登录页
      // localStorage.removeItem("token")
      localStorage.clear()
      history.push('/user/login');
    }
  };

  const dropdownMenu = <Menu items={items} onClick={handleMenuClick} />;

  const RobotAvatar: React.FC = () => (
    <span role="img" aria-label="robot">
      🤖
    </span>
  );

  return (
    <Layout style={{ height: '100vh' }}>
      <Sider
        width={300}
        theme="light"
        style={{
          borderRight: '1px solid #e8e8e8',
          backgroundColor: '#fafafa',
          display: 'flex',
          flexDirection: 'column',
          height: '100vh',
        }}
      >
        <div style={{ padding: 16, fontWeight: 'bold', fontSize: 18 }}>装修好帮手</div>
        <div style={{ padding: '8px 16px 16px' }}>
          <Button type="primary" icon={<PlusOutlined />} block onClick={handleNewChat}>
            新增对话
          </Button>
        </div>

        {/* 带文字的分隔线 */}
        <div
          style={{
            width: '100%',
            color: '#888',
            fontWeight: 'bold',
            textAlign: 'center',
            margin: '16px 0',
            position: 'relative',
            fontSize: 14,
            backgroundColor: '#fafafa',
          }}
        >
          <span
            style={{
              backgroundColor: '#fafafa',
              padding: '0 12px',
              position: 'relative',
              zIndex: 1,
            }}
          >
            历史对话
          </span>
          <div
            style={{
              position: 'absolute',
              top: '50%',
              left: 0,
              right: 0,
              borderTop: '1px solid #d9d9d9',
              transform: 'translateY(-50%)',
              zIndex: 0,
            }}
          />
          <div style={{ position: 'fixed', bottom: 10, left: 30 }}>
            <span>{`免费次数：${paidCount || 0}`}</span>
            <span style={{ marginLeft: 20 }}>{`付费次数：${freeCount || 0}`}</span>
          </div>
        </div>

        <Menu mode="inline" style={{ flex: 1, backgroundColor: '#fafafa' }}>
          {historyList.length > 0 ? (
            historyList.map((item) => (
              <Menu.Item
                key={item.cellId}
                onClick={() => loadConversation(item.cellId)}
                style={{ fontWeight: currentCellId === item.cellId ? 'bold' : 'normal' }}
              >
                {item.title}
              </Menu.Item>
            ))
          ) : (
            <Menu.Item disabled>暂无历史记录</Menu.Item>
          )}
        </Menu>
      </Sider>


      <Layout>
        <Header style={{ background: '#fff', paddingRight: 24, textAlign: 'right' }}>
          <Dropdown overlay={dropdownMenu} placement="bottomRight">
            <span style={{ cursor: 'pointer' }}>
              <Avatar icon={<UserOutlined />} style={{ marginRight: 8 }} /> 当前用户
            </span>
          </Dropdown>
        </Header>
        <Content style={{ background: '#fff', padding: 24, overflowY: 'auto', flex: 1 }}>
          <div style={{ maxWidth: 800, margin: '0 auto' }}>



            {/* 消息列表 */}
            {messages.length === 0 ? (
              <div style={{ color: '#aaa', textAlign: 'center', paddingTop: 100 }}>请开始对话...</div>
            ) : (
              <List
                dataSource={messages}
                style={{
                  height: '100%', // 或设置固定高度如'500px'
                  overflow: 'auto' // 确保可以滚动
                }}
                renderItem={(item) => (
                  <List.Item
                    style={{
                      justifyContent: item.type === 'user' ? 'flex-end' : 'flex-start',
                      border: 'none',
                      padding: '12px 0' // 添加一些内边距
                    }}
                  >
                    <div style={{
                      display: 'flex',
                      flexDirection: item.type === 'user' ? 'row-reverse' : 'row',
                      alignItems: 'flex-start',
                      gap: 8,
                      width: '100%' // 确保宽度填满
                    }}>
                      <Avatar
                        icon={item.type === 'user' ? <UserOutlined /> : <RobotAvatar />}
                        style={{ backgroundColor: item.type === 'user' ? '#1890ff' : '#f0f0f0', color: item.type === 'user' ? '#fff' : '#000' }}
                      />
                      <div>
                        <div
                          style={{
                            background: item.type === 'user' ? '#1890ff' : '#f5f5f5',
                            color: item.type === 'user' ? '#fff' : '#000',
                            padding: '10px 16px',
                            borderRadius: 8,
                            maxWidth: 500,
                            whiteSpace: 'pre-wrap',
                          }}
                        >
                          {item.text}
                        </div>
                        <div style={{ fontSize: 12, color: '#888', marginTop: 4, textAlign: item.type === 'user' ? 'right' : 'left' }}>
                          {item.time}
                        </div>
                      </div>
                    </div>
                  </List.Item>
                )}
              />
            )}

            {loading && (
              <div style={{ textAlign: 'center', marginTop: 16 }}>
                <span className="ant-spin-dot ant-spin-dot-spin">
                  <span className="ant-spin-dot-item"></span>
                  <span className="ant-spin-dot-item"></span>
                  <span className="ant-spin-dot-item"></span>
                  <span className="ant-spin-dot-item"></span>
                </span>
                &nbsp;思考中...
              </div>
            )}
          </div>
        </Content>

        <Footer style={{ background: '#fff', padding: 16 }}>
          <div
            style={{
              position: 'relative',
              border: '1px solid #fff',
              borderRadius: 4,
              padding: '8px',
            }}
          >

            {/* 已上传文件展示区域 —— 插在这里，位于输入框上方 */}
            {uploadedFiles.length > 0 && (
              <div style={{
                marginBottom: 12,
                padding: '8px 12px',
                backgroundColor: '#f8f8f8',
                borderRadius: 4,
                display: 'flex',
                flexWrap: 'wrap',
                gap: 8
              }}>
                {uploadedFiles.map((file, index) => (
                  <div key={index} style={{
                    display: 'flex',
                    alignItems: 'center',
                    backgroundColor: '#fafafa',
                    border: '1px solid #e8e8e8',
                    borderRadius: 4,
                    padding: '4px 8px',
                    gap: 6
                  }}>
                    <span role="img" aria-label="file">📄</span>
                    <span style={{ fontSize: 13 }}>{file?.name || ""}</span>
                    {file?.id && <Button
                      type="text"
                      icon={<span role="img" aria-label="delete">❌</span>}
                      onClick={(e) => {
                        e.stopPropagation();
                        setUploadedFiles(prev => prev.filter(f => f.id !== file.id));
                      }}
                      style={{ marginLeft: 4, padding: 0, width: 20, height: 20 }}
                    />}
                  </div>
                ))}
              </div>
            )}

            {/* 原始输入框保持不变 */}
            <TextArea
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onPressEnter={(e) => {
                if (!e.shiftKey) {
                  e.preventDefault();
                  handleSend();
                }
              }}
              placeholder="请输入内容..."
              rows={3}
              style={{
                paddingRight: 100,
                paddingLeft: 40,
                resize: 'none',
                height: 100,
              }}
            />

            {/* 上传按钮 - 左下角 */}
            <div style={{ position: 'absolute', bottom: 12, left: 12 }}>
              <Upload
                showUploadList={false}
                customRequest={({ file }) => handleFileUpload(file as File)}
                beforeUpload={(file) => {
                  // const isValid = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  //   file.type === 'application/vnd.ms-excel' ||
                  //   /\.(xls|xlsx)$/i.test(file.name);
                  // if (!isValid) {
                  //   message.error('只能上传 Excel 文件!');
                  //   return false;
                  // }
                  // return true;
                }}
              // accept=".xls,.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              >
                <Button type="link" icon={<UploadOutlined />} />
              </Upload>
            </div>

            {/* 发送按钮 - 右下角 */}
            <div style={{ position: 'absolute', bottom: 12, right: 12 }}>
              <Button type="primary" icon={<SendOutlined />} onClick={handleSend} loading={loading}>
                发送
              </Button>
            </div>
          </div>
        </Footer>
      </Layout>
    </Layout>
  );
};

export default App;